<?php

namespace Wanecho\Mobilelogin\Api\Listeners;

use Flarum\Foundation\AbstractValidator;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Validation\Validator;
use Flarum\User\User;

class AddValidatorRule
{
    /**
     * @var SettingsRepositoryInterface
     */
    protected $settings;
    /**
     * @param SettingsRepositoryInterface $settings
     */
    public function __construct(SettingsRepositoryInterface $settings)
    {
        $this->settings = $settings;
    }

    public function __invoke(AbstractValidator $flarumValidator, Validator $validator)
    {
        $validator->addExtension(
            'mobile',
            function ($attribute, $value, $parameters) {
                if(!preg_match("/^1[3457689]\d{9}$/", $value)){
                    return false;
                }
                $user = User::where(['mobile' => $value])->first();
                if(!$user){
                    return true;
                }
                return false;
            }
        );
        $validator->addExtension(
            'msgcode',
            function ($attribute, $value, $parameters) {
                return true;
            }
        );
    }
}